import { Button, Checkbox, Form, Input } from 'antd';
import React from 'react';
import * as api from "@/api/users"
import useStorage from '@/hooks/useStorage';
import { useNavigate } from "react-router-dom"
//校验函数

//校验用户名

const validatorUsername = (rules: any, value: string) => {
    if (!value) {
        return Promise.reject('输入不能为空')
    }
    //如果通过 返回Promise.resolve 如果不通过 返回Promise.reject
    if (value.length < 3) {
        return Promise.reject('用户名的长度不能少于3位')
    } else {
        return Promise.resolve()
    }
}
//登入请求传递参数的类型
declare global {
    interface loginParam {
        username: string;
        password: string;
        remember: boolean
    }
}

const Login: React.FC = () => {
    //使用自定义的本地存储
    let [, tokenMethod] = useStorage('qf-token');
    let [, userMethod] = useStorage('user-info');
    let [, permissionMethod] = useStorage('btn-permission');
    //跳转hook
    let navigate = useNavigate()
    //表单校验通过
    const onFinish = (values: loginParam) => {
        console.log('Success:', values);
        //发起登入请求
        api.loginApi(values)
            .then((res: any) => {
                // console.log(res)
                //如果登入成功
                if (res.data.state) {
                    //1.存token
                    tokenMethod.set(res.data.token)
                    //2.存用户信息
                    userMethod.set(res.data.userInfo)
                    //3.存按钮权限
                    permissionMethod.set(res.data.permission)
                    //4.跳转到主页
                    navigate("/")
                }
            })
    };

    //表单校验失败
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };

    return (
        <Form
            name="loginForm"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 5 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
        >
            <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, validator: validatorUsername }]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: '输入用户密码' }]}
            >
                <Input.Password />
            </Form.Item>

            <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 2, span: 5 }}>
                <Checkbox>七天免登入</Checkbox>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 2, span: 5 }}>
                <Button type="primary" htmlType="submit">
                    登入
                </Button>
            </Form.Item>
        </Form>
    );
};

export default Login